<template>
    <el-dialog v-model="visible" :title="book?.title || '书籍详情'" width="80%" :before-close="handleClose"
        custom-class="book-detail-dialog">
        <div class="book-detail-container">
            <!-- 第一部分：书籍基本信息 -->
            <div class="book-info-section">
                <!-- 左侧书籍图片 -->
                <div class="book-cover-container">
                    <img :src="book?.cover" :alt="book?.title" class="book-cover" />
                </div>

                <!-- 中间书籍信息 -->
                <div class="book-details">
                    <h2 class="book-title">{{ book?.title }}</h2>
                    <div class="book-meta">
                        <span class="author">作者：{{ book?.author }}</span>
                        <span class="status">状态：{{ bookStatus }}</span>
                        <span class="publish-date">发布时间：{{ formatDate(book?.publishDate) }}</span>
                    </div>
                    <div class="book-description">
                        <h3>作品描述</h3>
                        <p>{{ book?.description }}</p>
                    </div>
                </div>

                <!-- 右侧操作按钮 -->
                <div class="action-buttons">
                    <el-button class="action-btn" @click="handleReadBook">
                        <span class="btn-icon">📖</span>
                        <span class="btn-text">阅读书籍</span>
                    </el-button>
                    <el-button class="action-btn" @click="handleAddToShelf">
                        <span class="btn-icon">📚</span>
                        <span class="btn-text">{{ isInShelf ? '已收藏' : '加入书架' }}</span>
                    </el-button>
                    <el-button class="action-btn" @click="handleReport">
                        <span class="btn-icon">🚩</span>
                        <span class="btn-text">举报书评</span>
                    </el-button>
                    <!-- 修改：分享改为书评 -->
                    <el-button class="action-btn" @click="handleShowReviews">
                        <span class="btn-icon">💬</span>
                        <span class="btn-text">书评</span>
                    </el-button>
                </div>
            </div>

            <!-- 第二部分：目录 -->
            <div class="catalog-section">
                <h3 class="catalog-title">目录</h3>
                <!-- 修改：目录样式改为按钮样式 -->
                <div class="catalog-container">
                    <div v-for="chapter in catalog" :key="chapter.id" :class="['chapter-btn', `level-${chapter.level}`]"
                        @click="handleChapterClick(chapter)">
                        <span class="chapter-content">
                            <span class="chapter-title">{{ chapter.title }}</span>
                            <span v-if="chapter.pageCount" class="chapter-pages">{{ chapter.pageCount }}页</span>
                        </span>
                    </div>
                </div>
            </div>

            <!-- 书评对话框 -->
            <el-dialog v-model="reviewDialogVisible" title="书评" width="60%" append-to-body custom-class="review-dialog">
                <div class="review-container">
                    <!-- 发表评论区域 -->
                    <div class="review-input-section">
                        <h3>发表评论</h3>
                        <el-input v-model="newReview" type="textarea" :rows="3" placeholder="请输入您的评论..."
                            class="review-textarea" />
                        <div class="review-actions">
                            <el-button type="primary" @click="submitReview">提交评论</el-button>
                        </div>
                    </div>

                    <!-- 评论列表 -->
                    <div class="review-list">
                        <h3>评论列表</h3>
                        <div v-if="reviews.length > 0" class="reviews">
                            <div v-for="review in reviews" :key="review.id" class="review-item">
                                <div class="review-header">
                                    <span class="reviewer">{{ review.reviewer }}</span>
                                    <span class="review-date">{{ formatDate(review.date) }}</span>
                                </div>
                                <div class="review-content">
                                    {{ review.content }}
                                </div>
                            </div>
                        </div>
                        <div v-else class="no-reviews">
                            暂无评论，快来发表第一条评论吧！
                        </div>
                    </div>
                </div>
            </el-dialog>

            <!-- 举报对话框 -->
            <el-dialog v-model="reportDialogVisible" title="举报书评" width="400px" append-to-body>
                <el-form :model="reportForm" label-width="80px">
                    <el-form-item label="举报原因">
                        <el-select v-model="reportForm.reason" placeholder="请选择举报原因">
                            <el-option label="内容违规" value="violation" />
                            <el-option label="抄袭侵权" value="plagiarism" />
                            <el-option label="虚假信息" value="false_info" />
                            <el-option label="其他原因" value="other" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="详细说明" v-if="reportForm.reason">
                        <el-input v-model="reportForm.description" type="textarea" :rows="3" placeholder="请详细描述举报原因" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="reportDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitReport">提交举报</el-button>
                </template>
            </el-dialog>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

interface Book {
    id: number
    title: string
    cover: string
    description: string
    author: string
    publishDate: Date
    status?: string
}

interface Chapter {
    id: number
    title: string
    level: number
    pageCount?: number
    children?: Chapter[]
}

interface ReportForm {
    reason: string
    description: string
}

interface Review {
    id: number
    reviewer: string
    content: string
    date: Date
}

// 组件属性
const props = defineProps<{
    modelValue: boolean
    book: Book | null
}>()

// 组件事件
const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
}>()

// 弹窗显示状态
const visible = ref(false)
// 书架状态
const isInShelf = ref(false)
// 举报对话框可见性
const reportDialogVisible = ref(false)
// 书评对话框可见性
const reviewDialogVisible = ref(false)
// 举报表单
const reportForm = ref<ReportForm>({
    reason: '',
    description: ''
})
// 新评论
const newReview = ref('')

// 监听props变化
watch(() => props.modelValue, (val) => {
    visible.value = val
    if (val && props.book) {
        checkShelfStatus()
    }
})

// 目录数据
const catalog = ref<Chapter[]>([
    { id: 1, title: '第一章：引言', level: 1, pageCount: 12 },
    { id: 2, title: '第一节：背景介绍', level: 2, pageCount: 5 },
    { id: 3, title: '第二节：研究意义', level: 2, pageCount: 7 },
    { id: 4, title: '第二章：文献综述', level: 1, pageCount: 20 },
    { id: 5, title: '第一节：国内研究', level: 2, pageCount: 10 },
    { id: 6, title: '第二节：国外研究', level: 2, pageCount: 10 },
    { id: 7, title: '第三章：方法论', level: 1, pageCount: 15 },
    { id: 8, title: '第一节：研究方法', level: 2, pageCount: 8 },
    { id: 9, title: '第二节：数据分析', level: 2, pageCount: 7 },
    { id: 10, title: '第四章：案例分析', level: 1, pageCount: 25 },
])

// 评论数据
const reviews = ref<Review[]>([
    { id: 1, reviewer: '文学爱好者', content: '这本书写得非常精彩，内容丰富，值得一读！', date: new Date(2023, 5, 15) },
    { id: 2, reviewer: '书虫小张', content: '作者的观点很独特，给了我很多启发。', date: new Date(2023, 5, 10) },
    { id: 3, reviewer: '读书人', content: '已经读第二遍了，每次都有新的收获。', date: new Date(2023, 4, 28) }
])

// 书籍状态
const bookStatus = computed(() => {
    return props.book?.status || '已完成'
})

// 检查书籍是否已在书架
const checkShelfStatus = () => {
    // 模拟检查书架状态
    const shelfBooks = JSON.parse(localStorage.getItem('bookShelf') || '[]')
    isInShelf.value = shelfBooks.some((b: Book) => b.id === props.book?.id)
}

// 关闭弹窗
const handleClose = () => {
    visible.value = false
    emit('update:modelValue', false)
    // 重置表单
    reportForm.value = { reason: '', description: '' }
}

// 阅读书籍
const handleReadBook = async () => {
    if (!props.book) return

    try {
        // 模拟阅读操作
        ElMessage.success(`开始阅读《${props.book.title}》`)
        // 这里可以添加跳转到阅读页面的逻辑
        handleClose()
    } catch (error) {
        console.log(error)
        ElMessage.error('阅读失败，请重试')
    }
}

// 加入书架
const handleAddToShelf = async () => {
    if (!props.book) return

    try {
        if (isInShelf.value) {
            // 从书架移除
            const shelfBooks = JSON.parse(localStorage.getItem('bookShelf') || '[]')
            const updatedBooks = shelfBooks.filter((b: Book) => b.id !== props.book?.id)
            localStorage.setItem('bookShelf', JSON.stringify(updatedBooks))
            isInShelf.value = false
            ElMessage.success('已从书架移除')
        } else {
            // 添加到书架
            const shelfBooks = JSON.parse(localStorage.getItem('bookShelf') || '[]')
            shelfBooks.push(props.book)
            localStorage.setItem('bookShelf', JSON.stringify(shelfBooks))
            isInShelf.value = true
            ElMessage.success('已加入书架')
        }
    } catch (error) {
        console.log(error)
        ElMessage.error('操作失败，请重试')
    }
}

// 举报
const handleReport = () => {
    if (!props.book) return
    reportDialogVisible.value = true
}

// 显示书评
const handleShowReviews = () => {
    reviewDialogVisible.value = true
}

// 提交评论
const submitReview = () => {
    if (newReview.value.trim()) {
        reviews.value.unshift({
            id: reviews.value.length + 1,
            reviewer: '当前用户',
            content: newReview.value,
            date: new Date()
        })
        newReview.value = ''
        ElMessage.success('评论发表成功')
    } else {
        ElMessage.warning('请输入评论内容')
    }
}

// 提交举报
const submitReport = async () => {
    if (!reportForm.value.reason) {
        ElMessage.warning('请选择举报原因')
        return
    }

    try {
        // 模拟举报提交
        console.log('举报信息:', {
            book: props.book,
            report: reportForm.value
        })

        ElMessage.success('举报已提交，我们会尽快处理')
        reportDialogVisible.value = false
        reportForm.value = { reason: '', description: '' }
    } catch (error) {
        console.log(error)
        ElMessage.error('提交失败，请重试')
    }
}

// 选择章节
const handleChapterClick = (chapter: Chapter) => {
    ElMessage.info(`跳转到: ${chapter.title}`)
    // 这里可以添加跳转到具体章节的逻辑
}

// 格式化日期
const formatDate = (date?: Date): string => {
    if (!date) return '未知'
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}
</script>

<style scoped>
/* 样式保持不变，与之前相同 */
.book-detail-container {
    display: flex;
    flex-direction: column;
    gap: 25px;
}

.book-info-section {
    display: flex;
    gap: 25px;
    padding-bottom: 20px;
    border-bottom: 1px solid #d6c8b8;
}

.book-cover-container {
    flex-shrink: 0;
    width: 200px;
    height: 280px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(90, 62, 47, 0.15);
}

.book-cover {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.book-details {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.book-title {
    font-size: 24px;
    font-weight: 600;
    color: #5a3e2f;
    margin: 0;
}

.book-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
    font-size: 15px;
    color: #8b6152;
}

.book-description h3 {
    font-size: 18px;
    color: #5a3e2f;
    margin-bottom: 10px;
}

.book-description p {
    font-size: 15px;
    line-height: 1.6;
    color: #5a3e2f;
    margin: 0;
}

.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 15px;
    min-width: 140px;
}

.action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 80px;
    background-color: #f5efe6;
    border: 1px solid #d6c8b8;
    border-radius: 8px;
    padding: 10px;
    transition: all 0.3s ease;
}

.action-btn:hover {
    background-color: #e4d8c8;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(90, 62, 47, 0.1);
}

.btn-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.btn-text {
    font-size: 14px;
    font-weight: 500;
    color: #5a3e2f;
}

.catalog-section {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.catalog-title {
    font-size: 20px;
    font-weight: 600;
    color: #5a3e2f;
    margin: 0;
}

/* 修改：目录样式改为按钮样式 */
.catalog-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 12px;
    max-height: 300px;
    overflow-y: auto;
    padding: 5px;
}

/* 目录按钮样式 - 统一大小 */
.chapter-btn {
    display: flex;
    align-items: center;
    min-height: 60px;
    padding: 12px 15px;
    background-color: #fffaf3;
    border: 1px solid #d6c8b8;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    box-sizing: border-box;
}

.chapter-btn:hover {
    background-color: #e4d8c8;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(90, 62, 47, 0.1);
}

/* 不同级别的目录样式 */
.chapter-btn.level-1 {
    font-weight: 600;
    background-color: #f5efe6;
    border-left: 4px solid #5a3e2f;
    grid-column: 1 / -1;
}

.chapter-btn.level-2 {
    font-weight: 500;
    border-left: 2px solid #8b6152;
    margin-left: 20px;
}

.chapter-content {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.chapter-title {
    color: #5a3e2f;
    font-size: 14px;
    text-align: left;
    margin-bottom: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.chapter-pages {
    color: #7a9aae;
    font-size: 12px;
    align-self: flex-start;
}

.catalog-container::-webkit-scrollbar {
    width: 8px;
}

.catalog-container::-webkit-scrollbar-track {
    background: #f1e9e0;
    border-radius: 4px;
}

.catalog-container::-webkit-scrollbar-thumb {
    background: #8b6152;
    border-radius: 4px;
}

/* 书评弹窗样式 */
.review-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.review-input-section h3,
.review-list h3 {
    color: #5a3e2f;
    margin-bottom: 15px;
}

.review-textarea {
    margin-bottom: 15px;
}

.review-actions {
    display: flex;
    justify-content: flex-end;
}

.review-item {
    padding: 15px;
    border-bottom: 1px solid #e4d8c8;
}

.review-item:last-child {
    border-bottom: none;
}

.review-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.reviewer {
    font-weight: 600;
    color: #5a3e2f;
}

.review-date {
    color: #7a9aae;
    font-size: 13px;
}

.review-content {
    color: #5a3e2f;
    line-height: 1.5;
}

.no-reviews {
    text-align: center;
    color: #7a9aae;
    padding: 30px;
    font-style: italic;
}
</style>

<style>
/* 全局弹窗样式 */
.book-detail-dialog .el-dialog,
.review-dialog .el-dialog {
    border-radius: 12px;
    overflow: hidden;
    background-color: #f5efe6;
}

.book-detail-dialog .el-dialog__header,
.review-dialog .el-dialog__header {
    background-color: #5a3e2f;
    margin: 0;
    padding: 15px 20px;
}

.book-detail-dialog .el-dialog__title,
.review-dialog .el-dialog__title {
    color: #f5efe6;
    font-weight: 600;
}

.book-detail-dialog .el-dialog__headerbtn,
.review-dialog .el-dialog__headerbtn {
    top: 15px;
}

.book-detail-dialog .el-dialog__headerbtn .el-dialog__close,
.review-dialog .el-dialog__headerbtn .el-dialog__close {
    color: #f5efe6;
}

.book-detail-dialog .el-dialog__body,
.review-dialog .el-dialog__body {
    padding: 25px;
    background-color: #f5efe6;
}
</style>